#include "pgnparser.h"
#include <QStringList>
#include <QDebug>

PGNParser::PGNParser()
{
}

void PGNParser::setContent(QStringList lines)
{
    PGNGame tmpGame;
    foreach(QString line, lines)
    {
        if(line.contains("[") || line.contains("]"))
        {
            QPair<QString, QString> tagInfo = parseTags(line);
            if(tagInfo.first.trimmed().compare("Event", Qt::CaseInsensitive) == 0)
                tmpGame.setEvent(tagInfo.second);
            else if(tagInfo.first.trimmed().compare("Site", Qt::CaseInsensitive) == 0)
                tmpGame.setSite(tagInfo.second);
            else if(tagInfo.first.trimmed().compare("Date", Qt::CaseInsensitive) == 0)
                tmpGame.setDate(tagInfo.second);
            else if(tagInfo.first.trimmed().compare("Round", Qt::CaseInsensitive) == 0)
                tmpGame.setRound(tagInfo.second);
            else if(tagInfo.first.trimmed().trimmed().compare("White", Qt::CaseInsensitive) == 0)
                tmpGame.setWhitePlayersName(tagInfo.second);
            else if(tagInfo.first.trimmed().trimmed().compare("Black", Qt::CaseInsensitive) == 0)
                tmpGame.setBlackPlayersName(tagInfo.second);
            else
                qDebug()<<"Error (PGNParser (parsing tag) undefined tag: "<<tagInfo.first;
        }
        else if(line.contains(". "))
        {
            if(line.contains("1-0"))
            {
                tmpGame.setResult("1-0");
                line.remove(line.size()-4,4);
            }
            else if(line.contains("0-1"))
            {
                tmpGame.setResult("0-1");
                line.remove(line.size()-4,4);
            }
            else if(line.contains("1/2-1/2"))
            {
                tmpGame.setResult("1/2-1/2");
                line.remove(line.size()-8,8);
            }
            else if(line.contains("*"))
            {
                tmpGame.setResult("*");
                line.remove(line.size()-1,1);
            }
            tmpGame.setMoves(line);
            m_gamesInFile.push_back(tmpGame);
            tmpGame = PGNGame();
        }
    }
}

void PGNParser::debug()
{
    for(int i=0; i< m_gamesInFile.size(); i++)
        m_gamesInFile.at(i).debug();
}

QPair<QString, QString> PGNParser::parseTags(QString tagLine)
{
    qDebug()<<"Parsing: "<<tagLine;
    QPair<QString, QString> tagInfo;
    tagLine.remove(0,1);
    tagLine.remove(tagLine.size()-2,2);
    QStringList tag = tagLine.split(" \"");
    if(tag.size() > 1)
    {
        tagInfo.first = tag.at(0);
        tagInfo.second = tag.at(1);
    }
    else
        qDebug()<<"Syntax error in tagLine(PGNParser) line: "<<tagLine;
    return tagInfo;
}

QVector<PGNGame> PGNParser::games()
{
    return m_gamesInFile;
}
